// 文本宽度度量与简单 LRU 缓存
type CacheKey = string; // `${font}|${text}`

interface CacheEntry {
  width: number;
  lastUsed: number;
}

const cache = new Map<CacheKey, CacheEntry>();
const MAX_CACHE_SIZE = 500;

let canvas: HTMLCanvasElement | null = null;
let ctx: CanvasRenderingContext2D | null = null;

function ensureContext(): CanvasRenderingContext2D {
  if (!canvas) canvas = document.createElement('canvas');
  if (!ctx) ctx = canvas.getContext('2d');
  if (!ctx) throw new Error('Canvas 2D context not available');
  return ctx;
}

export function measureTextWidth(text: string, font: string): number {
  const key: CacheKey = `${font}|${text}`;
  const hit = cache.get(key);
  if (hit) {
    hit.lastUsed = performance.now();
    return hit.width;
  }
  const context = ensureContext();
  context.font = font;
  const metrics = context.measureText(text);
  const width = Math.ceil(metrics.width);
  cache.set(key, { width, lastUsed: performance.now() });
  if (cache.size > MAX_CACHE_SIZE) evictLRU();
  return width;
}

function evictLRU() {
  // 移除最久未使用的一批
  const entries = Array.from(cache.entries());
  entries.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
  const removeCount = Math.ceil(entries.length * 0.2);
  for (let i = 0; i < removeCount; i++) {
    cache.delete(entries[i][0]);
  }
}

export function getMeasureCacheSize(): number {
  return cache.size;
}



